import 'package:flutter/material.dart';
import 'package:flutter_module_pd/SizeUtils.dart';

import 'emoji_model.dart';

class EmojiText extends StatelessWidget {
  const EmojiText({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MyHomePage();
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
  }

  List<TextModel> xString(String text) {
    List<TextModel> list = [];
    RegExp mobile = RegExp(r"\[[\u4e00-\u9fa5]*?\]");
    bool isNext = true;
    String content = text;
    while (isNext) {
      isNext = mobile.hasMatch(content);
      if (isNext) {
        String? s = mobile.stringMatch(content);
        int i = content.indexOf(s!);
        if (i != 0) {
          list.add(TextModel(0, content.substring(0, i)));
        }
        list.add(TextModel(1, s));
        if (i + s.length >= content.length) {
          isNext = false;
        } else {
          content = content.substring(i + s.length, content.length);
        }
      } else {
        list.add(TextModel(1, content));
      }
    }
    return list;
  }

  List<InlineSpan> getText(String string) {
    List<TextModel> model = xString(string);

    List<InlineSpan> spans = [];
    for (int i = 0; i < model.length; i++) {
      var mode = model[i];
      //type 0文本 1表情
      if (mode.type == 0) {
        spans.add(TextSpan(text: mode.content));
      } else {
        spans.add(WidgetSpan(
            child: Image.asset(
          "resources/ic_wx_030.png",
          width: getWidth(24),
          height: getHeight(24),
          fit: BoxFit.contain,
        )));
      }
    }
    return spans;
  }

  @override
  Widget build(BuildContext context) {
    return RichText(
      text: TextSpan(
        style: TextStyle(color: Colors.red, fontSize: getSp(24)),
        children: getText("agasg[伤心]你好啊[[愤怒][高兴][很酷的][愤怒]]"),
      ),
    );
  }
}
